package com.mindskip.xzs.utility;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 封装Jackson的工具
 */
@Slf4j
public class JsonUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 反序列化的时候如果多了其他属性,不抛出异常
    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    // 将对象转换为字符串
    public static <T> String toJsonStr(T o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    // 将字符串转换为对象
    public static <T> T toJsonObject(String json, Class<T> valueType) {
        try {
            return objectMapper.readValue(json, valueType);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    // 将输入流转换为对象
    public static <T> T toJsonObject(InputStream stream, Class<T> valueType) {
        try {
            return objectMapper.<T>readValue(stream, valueType);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    // Json数组转换为List集合
    public static <T> List<T> toJsonListObject(String json, Class<T> valueType) {
        try {
            JavaType getCollectionType = objectMapper.getTypeFactory().constructParametricType(List.class, valueType);
            return objectMapper.readValue(json, getCollectionType);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


}
